import glob
import os
import re

import numpy as np
from matplotlib import pyplot as plt
import matplotlib as mpl

from stressPrinter.Model.AnkeDataAna import AnkeAna
from stressPrinter.Model import Globalvariables
from stressPrinter.Model.Globalvariables import STATION_ANKE


def ankePrinter(x,y1,y2,Tlabel):
    mpl.rcParams['font.size'] = 18
    plt.figure(figsize=(20, 7))
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
    #plt.title('5305轨道顺槽数据对比')
    plt.ylabel("Mpa")
    xc = [item for sublist in x for item in sublist]
    y1 = [item for sublist in y1 for item in sublist]
    y2 = [item for sublist in y2 for item in sublist]

    plt.plot(xc, y1)
    plt.plot(xc, y2)

    plt.xlim(0,len(x)*86400)
    plt.xticks(np.arange(0, (len(x))*86400, 86400),Tlabel)

    plt.legend(loc='upper left', bbox_to_anchor=(1, 1), fontsize=10)
    plt.tight_layout()
    plt.show()

    return 0

def initX(content):
    dayCount = 0
    x = []
    for i in content:
        dayCount += 1
        num = (dayCount-1)*86400
        xc = []
        for j in i:
            j += num
            xc.append(j)
        x.append(xc)
    return x

def initPath(station):
    foldPath = Globalvariables.ANEKFOLDPATH     #选择的路径
    pattern = os.path.join(foldPath, "*.xlsx")  # 匹配所有xlsx文件
    excel_files = glob.glob(pattern)

    anaName = []
    anaPath = []
    for name in station:
        key = re.search(r'\d+', name).group()
        value = STATION_ANKE.get(int(key))
        anaName.append(str(value))
    for excel_file in excel_files:
        filename = os.path.basename(excel_file)  # 获取文件名
        if "-" in filename:
            parts = filename.split("-")
            if parts[1] in anaName:
                anaPath.append(foldPath+'/'+excel_file.split('\\')[1])
    return anaPath
def initData():
    station = Globalvariables.ANKESTATION       #选择的台站
    AnaPath = initPath(station)
    ana = AnkeAna(AnaPath[0])

    keys = list(ana.data.keys())
    keys.pop(0)
    x = []
    y1 = []
    y2 = []
    for i in range(len(keys)):
        key = keys[i]
        x.append(ana.data[key][0])
        y1.append(ana.data[key][1])
        y2.append(ana.data[key][2])
    x = initX(x)
    ankePrinter(x,y1,y2,keys)






